package com.authentications.security;

import com.authentications.security.handler.JwtAuthenticationFilter;
import com.authentications.security.handler.JwtAuthorizationFilter;
import com.authentications.security.handler.JwtAuthenticationEntryPoint;
import com.authentications.security.handler.JwtAccessDeniedHandler;
import com.authentications.utils.JwtSpringSecurityTokenUtils;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * @ClassName WebSecurityConfig
 * @Author xiezhuocai
 * @Description SpringSecurity Adapter类
 * @Date 2021/12/18 11:46
 */
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private JwtSpringSecurityTokenUtils tokenUtils;

    public WebSecurityConfig(JwtSpringSecurityTokenUtils tokenUtils){
        this.tokenUtils = tokenUtils;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                //.antMatchers("/register").permitAll()
                //.antMatchers("/**").authenticated()
                // 其他都放行了
                .anyRequest().permitAll()
                //授权
                .and()
                .addFilter(new JwtAuthenticationFilter(authenticationManager(),tokenUtils))
                .addFilter(new JwtAuthorizationFilter(authenticationManager(),tokenUtils))
                // 禁用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //授权错误信息处理
                .exceptionHandling()
                //用户访问资源没有携带正确的token
                .authenticationEntryPoint(new JwtAuthenticationEntryPoint())
                //用户访问没有授权资源
                .accessDeniedHandler(new JwtAccessDeniedHandler());
        // 使用自己定义的拦截机制，拦截jwt
        //http.addFilterBefore(new JWTAuthorizationFilter(authenticationManager()),UsernamePasswordAuthenticationFilter.class)


    }
}

